package com.tangyh.lamp.tenant.service.impl;

import cn.hutool.core.convert.Convert;
import com.tangyh.basic.base.service.SuperCacheServiceImpl;
import com.tangyh.basic.cache.model.CacheKey;
import com.tangyh.basic.cache.model.CacheKeyBuilder;
import com.tangyh.basic.database.mybatis.conditions.Wraps;
import com.tangyh.basic.utils.BeanPlusUtil;
import com.tangyh.lamp.common.cache.tenant.DatasourceConfigCacheKeyBuilder;
import com.tangyh.lamp.tenant.dao.DatasourceConfigMapper;
import com.tangyh.lamp.tenant.dto.DataSourcePropertyDTO;
import com.tangyh.lamp.tenant.dto.DatasourceConfigSaveDTO;
import com.tangyh.lamp.tenant.entity.DatasourceConfig;
import com.tangyh.lamp.tenant.service.DatasourceConfigService;
import com.tangyh.lamp.tenant.strategy.InitSystemContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * <p>
 * 业务实现类
 * 企业
 * </p>
 *
 * @author zuihou
 * @date 2019-10-24
 */
@Slf4j
@Service

@RequiredArgsConstructor
public class DatasourceConfigServiceImpl extends SuperCacheServiceImpl<DatasourceConfigMapper, DatasourceConfig> implements DatasourceConfigService {

    private final InitSystemContext initSystemContext;

    @Override
    protected CacheKeyBuilder cacheKeyBuilder() {
        return new DatasourceConfigCacheKeyBuilder();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DatasourceConfig save(DatasourceConfigSaveDTO data) {
        // 1， 保存租户 (默认库)
        DatasourceConfig tenant = BeanPlusUtil.toBean(data, DatasourceConfig.class);
        // defaults 库
        save(tenant);
        return tenant;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        List<String> tenantCodeList = listObjs(Wraps.<DatasourceConfig>lbQ().select(DatasourceConfig::getId).in(DatasourceConfig::getId, ids), Convert::toStr);
        if (tenantCodeList.isEmpty()) {
            return true;
        }
        return removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteAll(List<Long> ids) {
        List<String> tenantCodeList = listObjs(Wraps.<DatasourceConfig>lbQ().select(DatasourceConfig::getId).in(DatasourceConfig::getId, ids), Convert::toStr);
        if (tenantCodeList.isEmpty()) {
            return true;
        }
        removeByIds(ids);
        return initSystemContext.delete(ids, tenantCodeList);
    }

    @Override
    public Boolean testConnect(DataSourcePropertyDTO model) {
        boolean flag = false;
        try {
            //加载驱动类
            Class.forName(model.getDriverClassName());
            Connection conn = DriverManager.getConnection(model.getUrl(), model.getUsername(), model.getPassword());
            if (conn != null) {
                flag = true;
            }
        } catch (Exception e) {
            log.error("测试连接数据源失败：{}", e.getMessage());
        }
        return flag;
    }
}
